/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    bool isCousins(TreeNode *root, int x, int y)
    {
        int xDepth = -1;
        int yDepth = -1;
        TreeNode *xParent = nullptr;
        TreeNode *yParent = nullptr;
        queue<pair<TreeNode *, TreeNode *>> q;
        q.push({root, nullptr});
        int depth = 0;
        while (!q.empty())
        {
            int qSize = q.size();
            for (int _ = 0; _ < qSize; ++_)
            {
                auto [node, parent] = q.front();
                q.pop();
                if (node->val == x)
                {
                    xDepth = depth;
                    xParent = parent;
                }
                else if (node->val == y)
                {
                    yDepth = depth;
                    yParent = parent;
                }

                if (node->left != nullptr)
                {
                    q.push({node->left, node});
                }
                if (node->right != nullptr)
                {
                    q.push({node->right, node});
                }
            }
            ++depth;
        }
        if (xDepth != yDepth)
        {
            return false;
        }
        return xParent != yParent;
    }
};